package services;

import dao.CollectionDAO;
import dao.ComicDAO;
import model.Collection;
import model.Comic_s;
import utils.C3P0Util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 收藏服务
 */
public class CollectionServices {

    private CollectionDAO collectionDAO;
    private Connection coon;

    public CollectionServices() {
        collectionDAO = new CollectionDAO();
        coon = C3P0Util.getConnection();
    }

    public void finish() {
        try {
            coon.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 添加收藏
     *
     * @param userName 用户名字
     * @param comicId  漫画id
     * @return true表示成功插入
     */
    public boolean addCollection(String userName, String comicId) {
        return collectionDAO.addCollection(userName, Integer.parseInt(comicId));
    }


    /**
     * 删除用户的一个收藏
     *
     * @param userName 用户名
     * @param comicId  漫画id
     * @return true表示成功
     */
    public boolean deleteCollection(String userName, String comicId) {

        System.out.println("now comicId:" + comicId);
        return collectionDAO.deleteCollection(userName, Integer.parseInt(comicId));
    }

    /**
     * 删除用户的多个收藏
     *
     * @param userName 用户名
     * @param comicIds 漫画id数组
     * @return true表示操作成功
     */
    public boolean deleteMultiCollection(String userName, String comicIds) {
        //comicIds = comicIds.replaceAll(",", " or ");
        comicIds = "(" + comicIds + ")";
        System.out.println("comicId:" + comicIds);
        return collectionDAO.deleteMultiCollection(userName, comicIds);
    }

    /**
     * 返回一个用户所有的收藏
     *
     * @param userName 用户名
     * @return list
     */
    public List<Collection> getUserAllCollection(String userName) {
        List<Collection> list = collectionDAO.getUserAllCollection(userName, coon);
        ComicDAO comicDAO = new ComicDAO();
        for (Collection collection : list) {//遍历collection
            Comic_s comic = comicDAO.getComic_sDetail(collection.getComic_id(), coon);
            collection.setComic(comic);//为每一个collection关联comic
        }
        return list;
    }

    /**
     * 检查用户是否已经收藏过该漫画了
     *
     * @param userName 用户名
     * @param comicId  漫画id
     * @return true表示已经收藏
     */
    public boolean isUserHaveCollection(String userName, String comicId) {
        return collectionDAO.isUserHaveCollection(userName, Integer.parseInt(comicId), coon);
    }

    /**
     * 获得某漫画的收藏数量
     *
     * @param comicId 漫画id
     * @return 数量
     */
    public int getCollectionCount(String comicId) {
        return collectionDAO.getCollectionCount(Integer.parseInt(comicId), coon);
    }
}